package com.zhao.data.test;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhao.test.UnitTesting;

public class RedisRunnerTesting extends UnitTesting {

	@Autowired
	ObjectMapper objectMapper;

	@Autowired
	RedisTemplate<String, Object> redisTemplate;

	@Test
	public void contextLoads() {

	}

	@Test
	public void testStringRedisTemplate() {
		String result = redisTemplate.execute(new RedisCallback<String>() {
			@Override
			public String doInRedis(RedisConnection connection) throws DataAccessException {
				connection.set("key1".getBytes(), "value1".getBytes());
				return new String(connection.get("key1".getBytes()));
			}
		});
		logger.debug("插入key：" + result);
		Long count = redisTemplate.execute(new RedisCallback<Long>() {
			@Override
			public Long doInRedis(RedisConnection connection) throws DataAccessException {
				return connection.del("key1".getBytes());
			}
		});
		logger.debug("刪除条数：" + count);
	}

	@Test
	public void opsRedisTemplate() {
		//		final Users user = new Users();
		//		user.setUsername("admin");
		//
		//		String result = redisTemplate.execute(new RedisCallback<String>() {
		//			@Override
		//			public String doInRedis(RedisConnection connection) throws DataAccessException {
		//				try {
		//					connection.set(user.getUsername().getBytes(), objectMapper.writeValueAsBytes(user));
		//				} catch (JsonProcessingException e) {
		//					e.printStackTrace();
		//				}
		//				return user.getUsername();
		//			}
		//		});
		//		logger.debug(result);
		//
		//		try {
		//			redisTemplate.opsForValue().set("user", user);
		//			Users value = (Users) redisTemplate.opsForValue().get("user");
		//			logger.debug("key值：" + value.getUsername());
		//		} catch (Exception e) {
		//			e.printStackTrace();
		//		}
		//
		//		redisTemplate.execute(new RedisCallback<Boolean>() {
		//			@Override
		//			public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
		//				RedisSerializer<String> redisSerializer = redisTemplate.getStringSerializer();
		//				connection.lPush("all".getBytes(), redisSerializer.serialize("1"), redisSerializer.serialize("2"));
		//				return true;
		//			}
		//		});
		//
		//		logger.debug("开始发布消息");
		//		try {
		//			RedisSerializer<String> redisSerializer = redisTemplate.getStringSerializer();
		//			redisTemplate.convertAndSend(redisSerializer.deserialize("chatroom".getBytes()), "Hello from Redis!");
		//		} catch (Exception e) {
		//			e.printStackTrace();
		//		}
	}
}
